package com.xiang.dao;

import com.xiang.pojo.Book;
import com.xiang.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDao {

    //创建核心类
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    //查询全部图书信息
    public List<Book> findAllBooks() {
        //定义sql
        String sql = "select * from book";
        //执行sql
        List<Book> list = null;
        try {
            list = qr.query(sql, new BeanListHandler<Book>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //新增图书信息
    public int addBook(Book book) {
        //定义sql
        String sql = "insert into book values (?,?,?,?,?)";
        Object[] param = {null, book.getBname(), book.getBprice(), book.getBauthor(), book.getBdesc()};
        //执行sql
        int r = 0;
        try {
            r = qr.update(sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return r;
    }

    //根据bid查询图书对象信息
    public Book findBookByBid(String bid) {
        String sql = "select * from book where bid = ?";
        Book book = null;
        try {
            book = qr.query(sql, new BeanHandler<Book>(Book.class), bid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;


    }

    //修改图书信息
    public int updateBook(Book book) {
        String sql = "update book set bname=?, bprice=?, bauthor=?, bdesc=? where bid=?";
        //赋值
        Object[] param = {book.getBname(), book.getBprice(), book.getBauthor(),
                book.getBdesc(), book.getBid()};
        //执行sql
        int r = 0;
        try {
            r = qr.update(sql, param);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return r;
    }

    //根据bid删除图书信息
    public int delBookByBid(String bid) {
        String sql = "delete from book where bid = ?";
        int r = 0;
        try {
            r = qr.update(sql, bid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return r;
    }
}
